import Big from 'big.js'
import dayjs from 'dayjs'

/** 数字转万元 */
export const formatToWan = (num: string | number): string => {
  const n = Number(num)
  if (isNaN(n)) return '0'
  const wan = n / 10000
  return wan.toFixed(Math.min(2, (`${wan}`.split('.')[1] || '').length)).replace(/\.?0+$/, '')
}

/** 数字转万元 */
export const formatToWanNum = (num: string | number): number => {
  const n = Number(num)
  if (isNaN(n)) return 0
  const wan = n / 10000
  return Number(
    wan.toFixed(Math.min(2, (`${wan}`.split('.')[1] || '').length)).replace(/\.?0+$/, ''),
  )
}

/** 数字转中文 */
export const numberToChinese = (num: number): string => {
  const chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
  if (num <= 10) {
    return chineseNums[num]
  }
  if (num < 20) {
    return '十' + (num % 10 === 0 ? '' : chineseNums[num % 10])
  }
  return chineseNums[Math.floor(num / 10)] + '十' + (num % 10 === 0 ? '' : chineseNums[num % 10])
}

/** 解析年月字符串 "2025-12" 格式 */
export function parseDate(dateStr: string) {
  const [year, month] = dateStr.split('-').map(Number)

  // 计算季度
  const quarter = Math.ceil(month / 3)

  return { year, month, quarter }
}

/** 生成图表标题 */
export function generateChartTitle(title: string) {
  return {
    text: `${title}`,
    left: 'center',
    top: '10%',
    textStyle: {
      fontSize: 16,
      // color: '#f8f8f8',
    },
  }
}

/** 根据指定字段分组并倒序排列 */
export function groupAndSortByField<T extends Record<string, any>>(array: T[], field: keyof T) {
  // 按字段分组
  const groupedData: Record<string, T[]> = {}
  array.forEach((item) => {
    const key = item[field]
    if (!groupedData[key]) {
      groupedData[key] = []
    }
    groupedData[key].push(item)
  })

  // 获取分组键并正序排序
  const sortedKeys = Object.keys(groupedData).sort((a, b) => b.localeCompare(a))

  // 返回排序后的分组数据
  return {
    groupedData,
    sortedKeys,
  }
}

/** 生成颜色数组 */
export function genColors() {
  return ['#4282ff', '#37e0cc', '#336bd3', '#ff7070', '#ffd66b', '#a26cf8', '#4282ff', '#37e0cc']
}

/**
 * 生成12月份的月份数组
 */
export function genMonthArray() {
  return Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
}

/**最多截止年份 */
const maxYear = dayjs().year() - 5

/**
 * 生成可选择的下拉框
 */
export function genSelectOptions(type: 'year' | 'quarter' | 'month' | 'week') {
  if (type === 'year') {
    const currentYear = new Date().getFullYear()
    const years = Array.from({ length: currentYear - maxYear }, (_, i) => currentYear - i)
    return years.map((year) => ({
      label: year + '年',
      value: year.toString(),
    }))
  }
  if (type === 'quarter') {
    return Array.from({ length: 4 }, (_, i) => `${i + 1}`).map((item) => ({
      label: item + '季度',
      value: item.toString(),
    }))
  }
  if (type === 'month') {
    return Array.from({ length: 12 }, (_, i) => `${i + 1}`).map((item) => ({
      label: item + '月',
      value: item.toString(),
    }))
  }
  if (type === 'week') {
    return Array.from({ length: 53 }, (_, i) => `${i + 1}`).map((item) => ({
      label: item + '周',
      value: item.toString(),
    }))
  }
}

export const customTableStyle = {
  class: 'custom-vxe-table flex-1',
  height: '550px',
  showFooter: true,
  // ✅ 1. 单元格样式（边框 + 交替背景）
  cellStyle: ({ rowIndex }: { rowIndex: number }) => {
    return {
      color: '#E0E7EE', // 文字颜色
      background: rowIndex % 2 === 0 ? '#11243D' : '#0c1c30', // 条纹背景
      border: '1px solid rgba(255, 255, 255, 0.1)', // 细边框
    }
  },

  // ✅ 2. 表头单元格样式（细边框）
  headerCellStyle: ({ columnIndex }: { columnIndex: number }) => {
    return {
      background: '#1E5A8A',
      color: '#E5F0FF',
      fontWeight: 'bold',
      borderBottom: columnIndex === 0 ? '2px solid #38A3D8' : '2px solid rgba(255, 255, 255, 0.2)', // 加强分隔
    }
  },

  // ✅ 3. 表尾单元格样式（蓝色背景）
  footerCellStyle: () => {
    return {
      background: '#1E5A8A',
      color: '#E5F0FF',
      fontWeight: 'bold',
      borderTop: '2px solid rgba(255, 255, 255, 0.2)',
    }
  },

  // ✅ 4. 行样式（交替背景 + 柔和边框）
  rowStyle: ({ rowIndex }: { rowIndex: number }) => {
    return {
      background: rowIndex % 2 === 0 ? '#11243D' : '#0c1c30',
    }
  },

  // ✅ 5. 表头行样式（加粗分隔）
  headerRowStyle: () => {
    return {
      borderBottom: '2px solid rgba(255, 255, 255, 0.2)',
    }
  },

  // ✅ 6. 表尾行样式（加粗分隔）
  footerRowStyle: () => {
    return {
      borderTop: '2px solid rgba(255, 255, 255, 0.2)',
    }
  },
}

/**
 * 计算表尾合计
 * @param list
 * @param field
 */
export const sumNum = (list: any[], field: string) => {
  let count = null
  list.forEach((item) => {
    if (typeof item[field] == 'number') {
      if (count == null) {
        count = new Big(0)
      }
      count = count.plus(item[field])
    }
  })

  return count
}

/**
 * 计算同比去年
 */
export const calcYoy = (current: number, last: number, decimal = 2) => {
  if (last === 0) {
    return '/'
  }
  const result = (((current || 0) - last) / last) * 100
  return isNaN(result) ? '0' : result.toFixed(decimal)
}
